package com.xz.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xz.usercenter.model.domain.User;
import com.xz.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.xz.usercenter.constant.LockConstant.RECOMMEND_USER_LOCK;

/**
 * @author xuzhou
 * @Description 预热推荐用户 定时任务
 */
@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    // 重点用户
    private List<Long> mainUserList = Collections.singletonList(1L);

    // 每天执行，预热推荐用户
    // 秒 分 小时
    @Scheduled(cron = "0 1 11 * * *")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock(RECOMMEND_USER_LOCK);
        try {
            // 只有一个线程能获取到锁
            // waitTime 设置为 0，只抢一次，抢不到就放弃
            // -1 可以自动续期
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                log.info("getLock: {}", Thread.currentThread().getId());
                for (Long userId : mainUserList) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    String redisKey = String.format("matching:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
                    // 写缓存 60 秒过期
                    try {
                        valueOperations.set(redisKey, userPage, 60000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            // 只能释放自己的锁
            // 注意释放锁要写在 finally 中
            if (lock.isHeldByCurrentThread()) {
                log.info("unLock: {}", Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }
}
